//
//  XMNavigationController.m
//  XMNavigationController
//
//  Created by Ce Liu on 2018/6/6.
//  Copyright © 2018年 Ce Liu. All rights reserved.
//

#import "XMNavigationController.h"

#import "UINavigationController+XM.h"

@interface XMNavigationController ()<UINavigationControllerDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIButton *backButton;

@end

@implementation XMNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    id target = self.interactivePopGestureRecognizer.delegate;
    
    SEL action = NSSelectorFromString(@"handleNavigationTransition:");
    
    //设置返回手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:target action:action];
    
    pan.delegate = self;
    
    [self.view addGestureRecognizer:pan];
    
    self.interactivePopGestureRecognizer.enabled = NO;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (self.childViewControllers.count >= 1) {
        return YES;
    } else {
        return NO;
    }
}


- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.childViewControllers.count > 0) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton addTarget:self action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
        [_backButton sizeToFit];
        [_backButton setImage:[UIImage imageNamed:self.backImage ? self.backImage : @"icon_back"] forState:UIControlStateNormal];
        _backButton.backgroundColor = [UIColor redColor];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_backButton];
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
    return [super popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

